package service

import (
	"ChdChat-Gin/initialize"
	"ChdChat-Gin/model"
	"gorm.io/gorm"
	"log"
)

func CreateChatGroup(info model.ChatGroups) (int64, error) {
	var (
		db *gorm.DB

		user  model.UserAccounts
		group model.ChatGroups
	)
	if db = initialize.Conn.
		Model(model.UserAccounts{}).
		Where("account = ?", info.Account).
		First(&user); db.RowsAffected > 0 {
		log.Printf("db.First:%v\n", ErrDataExist)
		return 0, ErrDataExist
	}
	if db = initialize.Conn.
		Model(model.ChatGroups{}).
		Where("account = ?", info.Account).
		First(&group); db.RowsAffected > 0 {
		log.Printf("db.First:%v\n", ErrDataExist)
		return 0, ErrDataExist
	}
	contact := &model.Contacts{
		User:    info.Master,
		Contact: info.Account,
		Type:    model.GROUP,
	}
	if err := initialize.Conn.Transaction(func(tx *gorm.DB) error {
		if tx = initialize.Conn.Create(info); tx.Error != nil {
			return tx.Error
		}
		if tx = initialize.Conn.Create(contact); tx.Error != nil {
			return tx.Error
		}
		return nil
	}); err != nil {
		log.Printf("db.Create:%v\n", err)
		return 0, ErrDatabase
	}
	return 1, nil
}

func DissolveChatGroup(account string) error {
	// TODO
	return nil
}

func UpdateChatGroupInfo(info *model.ChatGroups) error {
	// TODO
	return nil
}

func AddMembers(members []string) error {
	// TODO
	return nil
}

func DeleteMembers(members []string) error {
	// TODO
	return nil
}
